package univ.bme.accounting.beans;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import univ.bme.accounting.dao.CategoryDAO;
import univ.bme.accounting.domain.Category;
import univ.bme.accounting.beans.AccountingSessionBean;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor

@ManagedBean
@RequestScoped
public class CategoryMB extends MBUtils {

	@EJB
	private CategoryDAO categorydao;

	private Category category;
	
	@ManagedProperty("#{accountingSessionBean}")
	private AccountingSessionBean accountingSessionBean;
	
	@ManagedProperty("#{userMB}")
	private UserMB userMB;

	public Category getCategory() {
		
		if(category == null){
			category = new Category();
		}
		
		return category;
	}
	
	//Get all entries for the current user
	public List<Category> getAllCategories() {
		return categorydao.findCategoriesForUser(userMB.getCurrentRequestUser().getId());
	}
	
	public String updateCategory(){
		try {
			categorydao.update(category);
		} catch (EJBException e) {
			sendErrorMessageToUser(bundle.getString("operationFailed"));
			return null;
		}
		
		sendInfoMessageToUser(bundle.getString("operationCompleted"));
		return "listCategories";
	}
	
	public String deleteCategory(){
		try {
			categorydao.delete(category);
		} catch (EJBException e) {
			sendErrorMessageToUser(bundle.getString("operationFailed"));
			return null;
		}			
		
		sendInfoMessageToUser(bundle.getString("operationCompleted"));
		
		return "listCategories";
	}
	
	public String createCategory(){
		try {
			//Add the user from the session
			category.setUser(accountingSessionBean.getUser());
			//Save the category
			categorydao.save(category);
			
		} catch (EJBException e) {
			sendErrorMessageToUser(bundle.getString("operationFailed"));
			return null;
		}		
		sendInfoMessageToUser(bundle.getString("operationCompleted"));
		return "listCategories?faces-redirect=true";
	}
}